//
//  OMTKeychainAccessor.m
//  OMTCoreKit
//
//  Created by 昭荣伊 on 2018/7/27.
//

#import "OMTKeychainAccessor.h"

@implementation OMTKeychainAccessor

+ (NSMutableDictionary *)valueForService:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge id)kSecClassGenericPassword,(__bridge id)kSecClass,
            service, (__bridge id)kSecAttrService,
            service, (__bridge id)kSecAttrAccount,
            (__bridge id)kSecAttrAccessibleAfterFirstUnlock,(__bridge id)kSecAttrAccessible,
            nil];
}

+ (void)saveData:(id)data service:(NSString *)service {
    NSMutableDictionary *map = [self valueForService:service];
    SecItemDelete((__bridge CFDictionaryRef)map);
    [map setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
    SecItemAdd((__bridge CFDictionaryRef)map, NULL);
}

+ (id)dataForService:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *map = [self valueForService:service];
    [map setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [map setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge CFDictionaryRef)map, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}

+ (void)removeForService:(NSString *)service {
    NSMutableDictionary *map = [self valueForService:service];
    SecItemDelete((__bridge CFDictionaryRef)map);
}

@end
